<template>
	<el-dialog
		:title="props.editData ? '编辑车队' : '新增车队'"
		v-model="dialogVisible"
		width="500px"
		:close-on-click-modal="false"
		@close="handleClose"
	>
		<el-form
			ref="formRef"
			:model="formData"
			:rules="rules"
			label-width="100px"
			class="mt-4"
		>
			<el-form-item label="车队名称" prop="fleetName">
				<el-input v-model="formData.fleetName" placeholder="请输入车队名称" />
			</el-form-item>
			<el-form-item label="所属地区" prop="xzqh">
				<el-select
					v-model="formData.xzqh"
					placeholder="请选择地区"
					class="w-full"
					@change="handleRegionChange"
				>
					<el-option
						v-for="item in props.regionOptions"
						:key="item.value"
						:label="item.label"
						:value="item.value"
					/>
				</el-select>
			</el-form-item>
			<el-form-item label="负责人" prop="fleetLeader">
				<el-input
					v-model="formData.fleetLeader"
					placeholder="请输入负责人姓名"
				/>
			</el-form-item>
			<el-form-item label="联系电话" prop="telNumber">
				<el-input v-model="formData.telNumber" placeholder="请输入联系电话" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" @click="handleSubmit" :loading="loading">
					确定
				</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { addFleet, updateFleet } from '/@/api/tscompany/fleet';
import { ElMessage } from 'element-plus';

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false,
	},
	editData: {
		type: Object,
		default: null,
	},
	regionOptions: {
		type: Array,
		default: () => [],
	},
});

const emit = defineEmits(['update:modelValue', 'success']);

const dialogVisible = ref(false);
const loading = ref(false);
const formRef = ref(null);

// 表单数据
const formData = reactive({
	id: undefined,
	fleetName: '',
	xzqh: '',
	xzqhName: '',
	fleetLeader: '',
	telNumber: '',
});

// 表单校验规则
const rules = {
	fleetName: [{ required: true, message: '请输入车队名称', trigger: 'blur' }],
	xzqh: [{ required: true, message: '请选择所属地区', trigger: 'change' }],
	fleetLeader: [
		{ required: true, message: '请输入负责人姓名', trigger: 'blur' },
	],
	telNumber: [
		{ required: true, message: '请输入联系电话', trigger: 'blur' },
		{
			pattern: /^1[3-9]\d{9}$/,
			message: '请输入正确的手机号码',
			trigger: 'blur',
		},
	],
};

// 监听弹窗显示状态
watch(
	() => props.modelValue,
	(val) => {
		dialogVisible.value = val;
	},
);

// 监听弹窗关闭
watch(dialogVisible, (val) => {
	emit('update:modelValue', val);
	if (!val) {
		resetForm();
	}
});

// 监听编辑数据
watch(
	() => props.editData,
	(val) => {
		if (val) {
			Object.assign(formData, val);
		}
	},
	{ immediate: true },
);

// 地区选择变更处理
const handleRegionChange = () => {
	// 根据选中的xzqh值查找对应的地区名称
	const selectedRegion = props.regionOptions.find(
		(item) => item.value === formData.xzqh,
	);
	formData.xzqhName = selectedRegion ? selectedRegion.label : '';
};

// 重置表单
const resetForm = () => {
	formRef.value?.resetFields();
	Object.assign(formData, {
		id: undefined,
		fleetName: '',
		xzqh: '',
		xzqhName: '',
		fleetLeader: '',
		telNumber: '',
	});
};

// 关闭弹窗
const handleClose = () => {
	dialogVisible.value = false;
};

// 提交表单
const handleSubmit = async () => {
	if (!formRef.value) return;

	await formRef.value.validate((valid) => {
		if (valid) {
			loading.value = true;

			// 根据是否有id判断是新增还是编辑
			const apiCall = formData.id ? updateFleet(formData) : addFleet(formData);

			apiCall
				.then((response) => {
					if (response.code === 0) {
						ElMessage.success(formData.id ? '编辑成功' : '新增成功');
						emit('success', { ...formData });
						handleClose();
					} else {
						ElMessage.error(
							response.msg || (formData.id ? '编辑失败' : '新增失败'),
						);
					}
				})
				.catch((error) => {
					console.error(formData.id ? '编辑失败:' : '新增失败:', error);
					ElMessage.error(
						formData.id ? '编辑失败，请重试' : '新增失败，请重试',
					);
				})
				.finally(() => {
					loading.value = false;
				});
		}
	});
};
</script>
